package LeetCode.leetcode;

import domain.ListNode;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * 合并K个排序链表
 * @author: leiwenkang02@meituan.com
 * @date: 2018/9/26
 * @time: 16:28
 */
public class Test23合并K个排序链表 {

    //采用java提供的最小堆队列
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists==null||lists.length==0) {
            return null;
        }
        PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        ListNode before = new ListNode(0);
        ListNode p = before;

        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                priorityQueue.add(lists[i]);
            }
        }

        while (!priorityQueue.isEmpty()) {
            p.next = priorityQueue.poll();
            p = p.next;
            if (p.next != null) {
                priorityQueue.add(p.next);
            }
        }
        return before.next;
    }

    //归并排序 + 递归
    public ListNode mergeKLists2(ListNode[] lists) {
        if (lists==null||lists.length==0) {
            return null;
        }
        return merge(lists, 0, lists.length - 1);
    }

    public ListNode merge(ListNode[] lists, int start, int end) {
        if (start > end) {
            return null;
        }
        if (start == end) {
            return lists[start];
        }
        int mid = (start + end) / 2;
        ListNode listNode1 = merge(lists, start, mid);
        ListNode listNode2 = merge(lists, mid + 1, end);
        return merge(listNode1, listNode2);
    }

    public ListNode merge(ListNode listNode1, ListNode listNode2) {
        if (listNode1 == null) {
            return listNode2;
        }
        if (listNode2 == null) {
            return listNode1;
        }
        if (listNode1.val < listNode2.val) {
            listNode1.next = merge(listNode1.next, listNode2);
            return listNode1;
        } else {
            listNode2.next = merge(listNode1, listNode2.next);
            return listNode2;
        }

    }


}
